package Offer.offer2017;

/**
 * 顺时针打印矩阵
 * Created by 雷文康 on 2018/1/1.
 */
public class Test20 {
    public static void main(String[] args) {
        int[][] matrix={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        printMatrix(matrix);
    }
    public static void printMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
        int rows = matrix.length;
        int columns = matrix[0].length;
        int start = 0;
        while (rows > 2 * start && columns > 2 * start) {
            printCircle(matrix, rows, columns, start);
            start++;
        }
    }

    private static void printCircle(int[][] matrix, int rows, int columns, int start) {
        int endRow = rows - 1 - start;
        int endColumn = columns - 1 - start;
        for (int i = start; i <= endColumn; i++) {
            System.out.print(matrix[start][i]);
            System.out.print(" ");
        }
        if (endRow > start) {
            for (int i = start + 1; i <= endRow; i++) {
                System.out.print(matrix[i][endColumn]);
                System.out.print(" ");
            }
            if (endColumn > start) {
                for (int i = endColumn - 1; i >= start; i--) {
                    System.out.print(matrix[endRow][i]);
                    System.out.print(" ");
                }
                if (endRow > start + 1){
                    for (int i = endRow - 1; i > start ; i--) {
                        System.out.print(matrix[i][start]);
                        System.out.print(" ");
                    }
                }
            }
        }
    }

}
